package com.sxl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxl.domain.MenuInfo;
import com.sxl.domain.Modules;
import com.sxl.domain.Rolemodules;
import com.sxl.service.ModulesService;
import com.sxl.service.RolemodulesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.management.ObjectName;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: CRMProject
 * @Package: com.sxl.controller
 * @Author songxueliang
 * @Date 2022/4/27 16:40
 */
@RequestMapping("/menu")
@RestController
@CrossOrigin
public class MenuController {
    @Autowired
    private ModulesService modulesService;
    /**
     * 树状图
     */
    @GetMapping("/init")
    public Map<String, Object> init(Integer userId){

        List<MenuInfo> initList = modulesService.initMenu(userId, "c");
        //2、获取所有的一级菜单
        List<MenuInfo> rootMenu=new ArrayList<>();
        for(MenuInfo m:initList){
            if (m.getParentId()==-1){
                rootMenu.add(m);
            }
        }
        //3、设置一级菜单的子菜单
        for(MenuInfo m: rootMenu){
            //调用递归
            m.setChild(getChildren(m.getId(),initList));
        }
        //结果
        Map<String,Object> homeInfoMap=new HashMap<>();
        homeInfoMap.put("title","首页");
        homeInfoMap.put("href","page/welcome.html");
        Map<String,Object> logoInfoMap=new HashMap<>();
        logoInfoMap.put("title","crm");
        logoInfoMap.put("image","images/logo.png");
        logoInfoMap.put("href","");
        Map<String,Object> menuInfoMap=new HashMap<>();
        menuInfoMap.put("title","常规管理");
        menuInfoMap.put("icon","fa fa-address-book");
        menuInfoMap.put("href","");
        menuInfoMap.put("target","_self");
        menuInfoMap.put("child",rootMenu);
        List<Map<String, Object>> mapList = new ArrayList<>();
        mapList.add(menuInfoMap);
        Map<String,Object> rslMap = new HashMap<>();
        rslMap.put("homeInfo",homeInfoMap);
        rslMap.put("logoInfo",logoInfoMap);
        rslMap.put("menuInfo",mapList);
        return rslMap;
    }
    /**
     * 递归查找子菜单
     * @param pid
     * @param all
     * @return
     */
    private List<MenuInfo> getChildren(Integer pid,List<MenuInfo> all){
        List<MenuInfo> children=new ArrayList<>();//子菜单集合
        //、在所有菜单里面找父id=pid的
        for (MenuInfo m:all){
            if(m.getParentId()==pid){
                children.add(m);
            }
        }
        //2、递归找子的子....
        for (MenuInfo m:children){
            m.setChild(getChildren(m.getId(),all));
            }
        //3、递归退出
        if (children.size()==0){
            return new ArrayList<>();
        }
        return  children;
    }
}
